
$(document).ready(function () {
    //初始化加载按钮
    InitBtn();
    $('#excel-file').on("change",function(e){
        var files = e.target.files;
        var fileReader = new FileReader();
        fileReader.onload = function(ev) {
            try {
                var data = ev.target.result,
                    workbook = XLSX.read(data, {
                        type: 'binary'
                    }), // 以二进制流方式读取得到整份excel表格对象
                    persons = []; // 存储获取到的数据
            } catch (e) {
                console.log('文件类型不正确');
                bsEx.Alert("提示","文件类型不正确。<br/>请重新选择文件",3);
                $('#fileurl').val('');
                ReadXLSX.files = null;
                return;
            }
        
        }
        if(files && files[0]){
            $('#fileurl').val(files[0].name);
            var alltype = ["xls","xlsx"];
            var file_type=files[0].name.substring(files[0].name.lastIndexOf(".")+1);    
            if(alltype.indexOf(file_type)<0){
                console.log('文件类型不正确');
                bsEx.Alert("提示","文件类型不正确。<br/>请重新选择文件",3);
                $('#fileurl').val('');
                return;
            }else{
                // 以二进制方式打开文件
                fileReader.readAsBinaryString(files[0]);
                ReadXLSX.files = files[0];
            }
        }
    })
});

/**
 * 绘制按钮
*/
function InitBtn(){
   $('#btns').append('<p/><div id="btngroupid" class="btn-group"></div>&nbsp;&nbsp;');
    new bsEx.BtnGroup({
        renderto:"#btngroupid",
        btns:interfaceData
    });
    $('#btnfile').on('click',function(){
        $('#excel-file').click();
    })
} 

/**
 * 开始读取Excel 
 * 返回数组 [[{},{}...],[{},{}...]] 
 * 第一级数组包含sheet，第二级数组为行，第三级对象为数据*/
var ReadXLSX = function(fun){
    var fileReader = new FileReader();
    fileReader.onload = function(ev) {
        try {
            var data = ev.target.result,
                workbook = XLSX.read(data, {
                    type: 'binary'
                }), // 以二进制流方式读取得到整份excel表格对象
                persons = []; // 存储获取到的数据
                sheets = [];//存储获取到的Sheet名称
        } catch (e) {
            console.log('文件类型不正确');
            bsEx.Alert("提示","文件类型不正确。<br/>请重新选择文件",3);
            $('#fileurl').val('');
            $('#excel-file').files = {};
            return;
        }
        
         // 表格的表格范围，可用于判断表头是否数量是否正确
         var fromTo = '';
         // 遍历每张表读取
         for (var sheet in workbook.Sheets) {
             if (workbook.Sheets.hasOwnProperty(sheet)) {
                 fromTo = workbook.Sheets[sheet]['!ref'];
                 console.log(fromTo);
                 sheets.push(sheet);
                 persons.push(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                 // break; // 如果只取第一张表，就取消注释这行
             }
         }

         console.log(persons);

         bsEx.doCallback(fun,[persons,sheets]);
    }
    if(ReadXLSX.files){
        // 以二进制方式打开文件
        fileReader.readAsBinaryString(ReadXLSX.files);
    }else{
        bsEx.Alert("提示","文件类型不正确。<br/>请重新选择文件",3);
    }

}

//FileName 生成的Excel文件名称
var outExcel = function(FileName, JSONData, ShowLabel) {  
    //先转化json  
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;  
    
    if((!ShowLabel || ShowLabel.length==0) && arrData.length!=0){
        ShowLabel=[];
        for(var n in arrData[0]){
            var d = {};
            d[n] = n;
            ShowLabel.push(d);
        }
    }
    var excel = '<table>';      
      
    //设置表头  
    var row = "<tr align='left'>";//设置Excel的左居中
    for (var i = 0, l = ShowLabel.length; i < l; i++) {  
        for (var key in ShowLabel[i]) {
            row += "<td>" + ShowLabel[i][key] + '</td>';  
        }
    }  
      
      
    //换行  
    excel += row + "</tr>";  
      
    //设置数据  
    for (var i = 0; i < arrData.length; i++) {  
        var rowData = "<tr align='left'>"; 

        for (var y = 0; y < ShowLabel.length; y++) {
            for(var k in ShowLabel[y]){
                if (ShowLabel[y].hasOwnProperty(k)) {
                     rowData += "<td style='vnd.ms-excel.numberformat:@'>" + (arrData[i][k]===null? "" : arrData[i][k]) + "</td>";
　　　　　　　　　　　　　　　　　 //vnd.ms-excel.numberformat:@ 输出为文本
                }
            }
        }

        excel += rowData + "</tr>";  
    }  

    excel += "</table>";  

    var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";  
    excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';  
    excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';  
    excelFile += '; charset=UTF-8">';  
    excelFile += "<head>";  
    excelFile += "<!--[if gte mso 9]>";  
    excelFile += "<xml>";  
    excelFile += "<x:ExcelWorkbook>";  
    excelFile += "<x:ExcelWorksheets>";  
    excelFile += "<x:ExcelWorksheet>";  
    excelFile += "<x:Name>";  
    excelFile += "没想好QQ:935732994";  
    excelFile += "</x:Name>";  
    excelFile += "<x:WorksheetOptions>";  
    excelFile += "<x:DisplayGridlines/>";  
    excelFile += "</x:WorksheetOptions>";  
    excelFile += "</x:ExcelWorksheet>";  


    excelFile += "</x:ExcelWorksheets>";  
    excelFile += "</x:ExcelWorkbook>";  
    excelFile += "</xml>";  
    excelFile += "<![endif]-->";  
    excelFile += "</head>";  
    excelFile += "<body>";  
    excelFile += excel;     
    excelFile += "</body>";  
    excelFile += "</html>";  

      
    var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);  
      
    var link = document.createElement("a");   
    var iframe = document.createElement("iframe");    
    iframe.id = "_iframe";
    iframe.style = "height:0px;width:0px;border:none;"
    document.body.appendChild(iframe);  
    setTimeout(function(){

        var _iframe = document.getElementById("_iframe");
        var iwindow = _iframe.contentWindow;
        var idoc = iwindow.document;
        link.href = uri;  
        link.id = '_link';
        link.style = "visibility:hidden";  
        link.download = FileName + ".xls";  
        idoc.body.appendChild(link);  
        var _link = idoc.getElementById("_link");
        _link.click();  
        setTimeout(function(){
            document.body.removeChild(iframe);   
        },220)
        //idoc.body.removeChild(link);  
    },120)
}  